﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;
using System.Threading;

namespace WatchDog
{
     class ZombieProcess : Process
    {
        private void OnProcessTerminated(object sender, System.EventArgs e)
        {
            Console.WriteLine("aaa {0}", ((ZombieProcess)sender)._count_of_born_again);
            Console.WriteLine("[INFO] Process was terminated: PID({0}), ExitCode({1}), BornAgain({2})", Id, ExitCode, ++_count_of_born_again);
            Thread.Sleep(500);
            Start();
        }
        public void SetStartInfo(string filename, string arguments)
        {
            _filename = filename;
            _arguments = arguments;

            EnableRaisingEvents = true;
            Exited += new EventHandler(OnProcessTerminated);

            StartInfo.UseShellExecute = false;
            StartInfo.FileName = _filename;
            StartInfo.Arguments = _arguments;
            //StartInfo.WorkingDirectory = ..
            StartInfo.CreateNoWindow = true;
        }

        private string _filename;
        private string _arguments;
        private int _count_of_born_again;
    }

    class Program
    {
        private static string GetParamStringFromArgs(string[] args)
        {
            string arguments = "";
            for (int i = 1; i < args.GetLength(0); ++i)
            {
                if (-1 == args[i].IndexOf(' '))
                    arguments += args[i] + " ";
                else
                    arguments += "\"" + args[i] + "\" ";
            }
            arguments.Trim();
            return arguments;
        }
        static void Main(string[] args)
        {
            if (0 == args.GetLength(0))
            {
                Console.WriteLine("[INFO] Syntax: WatchDog.exe filename [params]");
                return;
            }

            string filename = args[0];
            string arguments = GetParamStringFromArgs(args);

            if (!System.IO.File.Exists(filename))
            {
                Console.WriteLine("[ERR ] File not found: {0}", filename);
                return;
            }

            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine("Create a Zombie Process: {0} {1}", filename, arguments);

            ZombieProcess zombie = new ZombieProcess();
            zombie.SetStartInfo(filename, arguments);
            zombie.Start();

            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine("Press ENTER to exit......");
            Console.ReadLine();
        }
    }
}
